type Subscriber<T> = {
  update : (msg:T) => void
}
interface IMessage {
  message : string,
  date? : string,
  user : string
}

// 发布订阅
// 发布订阅的类
class Publisher<U> {
  // 存储订阅者
  private subscribers: Array<Subscriber<U>>;
  constructor() {
    // 初始化订阅者数组
    this.subscribers = [];
  }
  // 订阅
  subscribe(subscriber : Subscriber<U>):void {
    // 将订阅者添加到订阅者数组中
    this.subscribers.push(subscriber);
  }
  // 取消订阅
  unsubscribe(subscriber: Subscriber<U>):void {
    // 将订阅者从订阅者数组中移除
    this.subscribers = this.subscribers.filter((item) => item !== subscriber);
  }
  // 发布消息
  publish(message :U):void {
    // 将消息传递给每一个订阅者
    this.subscribers.forEach((item) => item.update(message));
  }
}

const publisher = new Publisher<IMessage>();
// 订阅者先订阅
publisher.subscribe(
  {
    update(msg:IMessage) {
      console.log(`${msg.user} : ${msg.message}`)
    }
  }
)

publisher.subscribe(
  {
    update(msg:IMessage) {
      console.log(`${msg.user} : ${msg.message}`)
    }
  }
)

// 发布消息
publisher.publish({
  message : 'hello',
  user : '张三',
  date : new Date().toLocaleDateString()
})